
import UIKit
class TF_LivingAsk: TF_TopRightOrCornerTopLeft, UITableViewDelegate, UITableViewDataSource {
    @objc public var isShowAsk:Bool = false
    @objc public let title = UIButton()
    @objc public let pageScrollView = UIScrollView()
    @objc public let tableView = UITableView()
    @objc public let askMsg = UIButton()
    @objc public let askBtn = UIButton()
    @objc public let textView = TF_TextView()
    @objc public let textViewButton = UIButton()

    var KeyboardHeight:CGFloat = 0
    
    let line = UIView()
    let line1 = UIButton()
    var array = NSMutableArray()
    
    /*
     监听键盘的即将显示
     */
    @objc func keyboardWillShow(noti:NSNotification)
    {
    
        self.isShowAsk = true
   
           //不是聊天不用处理
        if (self.currentTextView(self.textView) == true) {
                
            }else{
                
                return;
                
            }
        let keyboardInfo:NSDictionary = noti.userInfo! as NSDictionary
        
        let keyboardFrameEnd:NSValue = keyboardInfo.value(forKey: UIResponder.keyboardFrameEndUserInfoKey) as! NSValue
        
        let frame:CGRect = keyboardFrameEnd.cgRectValue
        self.KeyboardHeight = frame.size.height;
        // 修改底部约束
         let  chatBarY:CGFloat = TalkfunSharedTools.getMainScreen().size.height - frame.size.height - self.frame.size.height
    
         let animationDuration:NSNumber = keyboardInfo.value(forKey: UIResponder.keyboardAnimationDurationUserInfoKey) as! NSNumber
         //  执行动画
         let duration = animationDuration.floatValue
        UIView.animate(withDuration: TimeInterval(duration)) {
            self.frame = CGRect(x: 0, y: chatBarY, width:  self.frame.size.width, height: self.frame.size.height)
        }

        
    }
    /**
     *  监听键盘的即将隐藏
     */
    @objc func KeyboardWillHide(noti:NSNotification)
    {
        if self.isShowAsk  {
            self.isShowAsk = false
    
            if (self.currentTextView(self.textView) == true) {
            
            let keyboardInfo:NSDictionary = noti.userInfo! as NSDictionary
            
            let animationDuration:NSNumber = keyboardInfo.value(forKey: UIResponder.keyboardAnimationDurationUserInfoKey) as! NSNumber
            //  执行动画
            let duration = animationDuration.floatValue
            
        
            let  chatBarY:CGFloat = TalkfunSharedTools.getMainScreen().size.height - self.frame.size.height;
            
            UIView.animate(withDuration: TimeInterval(duration)) {
                self.frame = CGRect(x: 0, y: chatBarY, width:  self.frame.size.width, height: self.frame.size.height)
            }
        
    }
        }
           
}
    override init(frame: CGRect) {
        super.init(frame: frame)
        //键盘显示前
        NotificationCenter.default.addObserver(self, selector: #selector(self.keyboardWillShow(noti:)), name: UIResponder.keyboardWillShowNotification, object: nil)

        //键盘隐藏前
        NotificationCenter.default.addObserver(self, selector: #selector(self.KeyboardWillHide(noti:)), name: UIResponder.keyboardWillHideNotification, object: nil)
        
        self.title.setTitle("提问" , for: .normal)
        self.title.titleLabel!.font = UIFont.PingFang(size: 16)
        self.title.backgroundColor = UIColor(red: 255/255.0, green: 255/255.0, blue: 255/255.0, alpha: 1.0)
        self.title.setTitleColor(UIColor(red: 35/255.0, green: 57/255.0, blue: 64/255.0, alpha: 1), for: .normal)
        self.addSubview(self.title)
        self.title.addTarget(self, action: #selector(self.openTitle), for: .touchUpInside)
    
       //线
       self.line.backgroundColor = UIColor(red: 238/255.0, green: 238/255.0, blue: 239/255.0, alpha: 1)
       self.title.addSubview(self.line)

       self.tableView.delegate = self;
       self.tableView.dataSource = self;
       self.tableView.backgroundColor = UIColor(red: 255/255.0, green: 255/255.0, blue: 255/255.0, alpha: 1)
       self.addSubview(self.tableView)
        self.tableView.separatorStyle = .none;
        self.tableView.separatorInset = .zero;

       self.askMsg.backgroundColor = UIColor(red: 255/255.0, green: 255/255.0, blue: 255/255.0, alpha: 1)
        self.askMsg.layer.shadowColor = UIColor(red: 0/255.0, green: 0/255.0, blue: 0/255.0, alpha: 0.08).cgColor

        self.askMsg.layer.shadowOffset = CGSize(width: 0, height: -0.5)
       self.askMsg.layer.shadowRadius = 0
       self.askMsg.layer.shadowOpacity = 1
        self.addSubview(self.askMsg)

       self.line1.backgroundColor = UIColor(red: 238/255.0, green: 238/255.0, blue: 239/255.0, alpha: 1)
        self.askMsg.addSubview(self.line1)
        
        self.askMsg.addTarget(self, action: #selector(self.openTitle), for: .touchUpInside)
     
 
       //TODO:提问按键
        self.askBtn.setTitle("提问", for: .normal)
        self.askBtn.titleLabel!.font = UIFont.PingFang(size: 15)
       self.askBtn.backgroundColor = UIColor(red: 1/255.0, green: 194/255.0, blue: 255/255.0, alpha: 1)
       self.askBtn.layer.cornerRadius = 17.5
        self.askMsg.addSubview(self.askBtn)
       //TODO:输入内容
        self.textView.font = UIFont.PingFang(size: 14)
        self.textView.tf_placeholder = "我要提问"
//       self.textView.leftMargin = "15";
       self.textView.backgroundColor = UIColor(red: 244/255.0, green: 246/255.0, blue: 248/255.0, alpha: 1)
        textView.showsVerticalScrollIndicator = false
        textView.showsHorizontalScrollIndicator = false
       self.askMsg.addSubview(self.textView)
        let toolbar = UIToolbar()
        toolbar.sizeToFit()

        let doneButton = UIBarButtonItem(title: "完成", style: .done, target: self, action: #selector(password_doneButtonTapped))
        toolbar.items = [UIBarButtonItem(barButtonSystemItem: .flexibleSpace, target: nil, action: nil), doneButton]
        textView.inputAccessoryView = toolbar
      
        self.tableView.register(TF_LivingAskCell.self, forCellReuseIdentifier: "TF_LivingAskCell")
    }
    @objc func password_doneButtonTapped() {
        self.textView.resignFirstResponder()
    }
    @objc func openTitle()
    {
        
    }
    override func layoutSubviews() {
        super.layoutSubviews()
        self.title.frame = CGRect(x: 0, y: 0, width: self.frame.size.width, height: 44)
        self.title.layer.cornerRadius = 10
        self.line.frame = CGRect(x: 0, y: self.title.frame.size.height - 0.5, width: self.title.frame.size.width, height: 0.5)
       
       self.askMsg.frame = CGRect(x: 0, y: self.frame.size.height - 50, width: self.frame.size.width, height: 50)
        
        self.tableView.frame = CGRect(x: 0, y: self.title.frame.maxY, width: self.frame.size.width, height: self.frame.size.height-self.title.frame.maxY-self.askMsg.frame.size.height)

        self.line1.frame = CGRect(x: 0, y: 0, width: self.title.frame.size.width, height: 0.5)
       
       self.askBtn.frame = CGRect(x: self.askMsg.frame.size.width - 55 - 15, y: (self.askMsg.frame.size.height - 30)/2, width: 55, height: 30) 
       self.textView.frame = CGRect(x: 15, y: (self.askMsg.frame.size.height - 35)/2, width: self.askBtn.frame.origin.x - 15 - 15, height: 35)

       self.textView.layer.cornerRadius = 17.5;
        self.initMask()
        
    }
    
    // cell的个数
      func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
          return self.array.count
      }
      // UITableViewCell
      func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
      
          let cell = tableView.dequeueReusableCell(withIdentifier: "TF_LivingAskCell", for: indexPath) as! TF_LivingAskCell
        
          let model = self.array[indexPath.row] as! TFQuestionData
          let url:URL? = URL.init(string:model.avatar)
          cell.questionerAvatar.sd_setImage(with: url, completed: nil)
          cell.viewWidth = self.frame.size.width;
          cell.viewHeight = self.tableView2(tableView, heightForRowAt: indexPath)
          cell.model = model;
          cell.backgroundColor = UIColor.clear
          cell.selectionStyle = .none

          return cell
      }
    
    // 设置cell高度
      func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {

          return self.tableView2(tableView, heightForRowAt: indexPath);
    
      }
    func tableView2(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {

      let model = self.array[indexPath.row] as! TFQuestionData
       
      let String = TalkfunSharedTools.getAttributedText(model.content, fontSize: UIFont.PingFang(size: 16), foregroundColor: UIColor.white)
       
      let size11 = TalkfunSharedTools.getSizeLabel(labelString: String, labelWidth:self.frame.size.width - 52 - 19, labelfont: UIFont.PingFang(size: 16))
        
            
            //老师回复了
            
        let answer:NSMutableArray = model.answer
                
        var  contentHight:CGFloat = 0
        
        
        for i in stride(from: 0, to: answer.count ,by: 1) {

            let dict2:TFQuestionAnswer = answer[i] as! TFQuestionAnswer
            
            let string2 = TalkfunSharedTools.getAttributedText(dict2.content, fontSize: UIFont.PingFang(size: 16), foregroundColor: UIColor.white)
             
            let size2 = TalkfunSharedTools.getSizeLabel(labelString: string2, labelWidth:self.frame.size.width - 79 - 19, labelfont: UIFont.PingFang(size: 16))
            
            
          //33
          contentHight = contentHight + size2.height + 33;
    
      

       
      }
        
        //提问的高度   + contentHight 回复的高度
      var viewHeight:CGFloat = size11.height+41.5+11+contentHight
            //5是间距
      if (answer.count>0) {
          viewHeight = viewHeight+(CGFloat((answer.count-1))*5);
      }
        
            
     return viewHeight;
  
    }
    //回复删除
    @objc public func replyTodeleteUI(model:TFQuestionData)

    {
     
        for i in stride(from: 0, to: self.array.count ,by: 1) {

            let obj = self.array[i] as! TFQuestionData
            
               if obj.qid == model.qid
            {
                   
                   let deleteQuestionID:NSString = model.deleteQuestionID as NSString
                   //删除某个问题下的其中一个回复
                   if (deleteQuestionID.length > 0) {
                       for i in stride(from: 0, to: obj.answer.count ,by: 1) {
                           
                         let answerModel = obj.answer[i] as! TFQuestionAnswer

                           if (answerModel.qid == deleteQuestionID as String) {
                               obj.answer.remove(answerModel)

                               break;
                               
                           }
                       }
                       
                   }
                   
                   else{
                       //整个问题删除
                       self.array.remove(obj)

                        break;
                      
                   }
                      
               }
              
           }
        self.tableView.reloadData()

    }
    //回复提问
    @objc public func questionPeplyUI(model:TFQuestionData)
    {
         
        var answer:Bool = false
        for i in stride(from: 0, to: self.array.count ,by: 1) {
     
            let obj = self.array[i] as! TFQuestionData
                //本地自己的提问中是否查询到
            if obj.qid == model.qid
            {
                     answer = true
                self.array.replaceObject(at: i, with: model)
             
                    break;
                }
                
            }
            
            //新增新的
            if (answer == false) {
                self.array.add(model)
            }
        self.tableView.reloadData()
    }
    
    @objc public func addQskQuestionsDictUI(model:TFQuestionData)
 
    {
        for i in stride(from: 0, to: self.array.count ,by: 1) {
     
            let obj = self.array[i] as! TFQuestionData

            if obj.qid == model.qid
            {
                
              return
            }
          }

    self.array.add(model)
      
    self.tableView.reloadData()
    if(self.array.count>0)
    {
        
    let indexpath = NSIndexPath.init(row: self.array.count - 1, section: 0)
    self.tableView.scrollToRow(at: indexpath as IndexPath, at: .bottom, animated: true)
    }

          
    }
    
    @objc public func updatedQuestionListUI(array:NSArray)

    {
        self.array.removeAllObjects()

        self.array.addObjects(from: array as! [Any])

        self.tableView.reloadData()
           
        if(self.array.count>0)
        {
            
        let indexpath = NSIndexPath.init(row: self.array.count - 1, section: 0)
        self.tableView.scrollToRow(at: indexpath as IndexPath, at: .bottom, animated: true)
        }
    }
    @objc public func destroySharedIntance()
    {
        NotificationCenter.default.removeObserver(self)
    }
    required init?(coder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
}
